#include "task/context.h"
#include <unordered_map>
#include <string>
#include <mutex>

namespace task
{
class ContextData
{
private:
    friend class Context;
    std::unordered_map<std::string, std::any> data_map_;
    std::mutex data_map_mutex_;
};
}

namespace task
{
Context::Context()
    : d(std::make_unique<ContextData>())
{

}
Context::~Context() = default;

void Context::setData(const std::string &name, std::any &value)
{
    std::lock_guard<std::mutex> lock_guard(d->data_map_mutex_);
    d->data_map_[name] = value;
}
std::any Context::getData(const std::string &name, bool *is_ok) const
{
    std::lock_guard<std::mutex> lock_guard(d->data_map_mutex_);
    if (d->data_map_.find(name) == d->data_map_.end())
    {
        *is_ok = false;
        return {};
    }
    *is_ok = true;
    return d->data_map_.at(name);
}
bool Context::exist(const std::string &name) const
{
    std::lock_guard<std::mutex> lock_guard(d->data_map_mutex_);
    return d->data_map_.find(name) != d->data_map_.end();
}
std::vector<std::string> Context::getAllDataKey() const
{
    std::vector<std::string> key_lists;
    std::lock_guard<std::mutex> lock_guard(d->data_map_mutex_);
    auto iter = d->data_map_.begin();
    for (; iter != d->data_map_.end(); ++iter)
    {
        key_lists.push_back(iter->first);
    }
    return key_lists;
}
}
